package com.gm.lib.net;

import com.gm.common.context.GlobalContext;
import com.gm.common.utils.LogUtil;
import com.gm.common.utils.NetUtil;
import com.gm.common.utils.ResUtil;
import com.gm.common.utils.StringUtils;
import com.gm.lib.R;
import com.gm.lib.cache.CacheApi;
import com.gm.lib.cache.CacheMode;
import com.gm.lib.model.GMRequestModel;
import com.gm.lib.model.ResultModel;
import com.gm.lib.utils.GMToastUtil;
import com.gm.lib.utils.JsonUtil;
import com.gm.net.ApiHandler;
import com.google.gson.JsonParseException;
import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Created by cx on 15/4/21.
 */
public abstract class GMApiHandler<T> extends ApiHandler {

    public static final String KEY_SUCCEED = "succeed";


    public static final String KEY_MESSAGE = "err";
    public static final String KEY_DATA = "data";


    public GMRequestModel gmRequestModel;

    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
        super.onSuccess(statusCode, headers, responseBody);
        //去掉协议里的垃圾
        String resultData = new String(responseBody);

        LogUtil.v("%s--> onSuccess %s", gmRequestModel.jsonCls.getName(), resultData);

        //协议里的json转换
        try {
            JSONObject jsonObject = new JSONObject(resultData);

            JSONObject jsonSucceed = jsonObject.optJSONObject("status");
            //取结果，即 result
            int code = jsonSucceed.getInt(KEY_SUCCEED);
            if (ApiCode.CODE_SUCCESS == code) {
                if (jsonObject.isNull("data")) {
                    //取不到data,直接返回
                    handleData(resultData);
                } else {
                    //取data里的值解析
                    handleData(jsonObject.getString(KEY_DATA));
                }
            } else {
                String message = "";
                ResultModel err = new ResultModel(code, message);
                onGMFail(err);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
        super.onFailure(statusCode, headers, responseBody, error);

        onNetFail(new ResultModel(statusCode, ResUtil.getString(R.string.error_no_net)));
        try {

            String errorStr = "";
            if (responseBody != null) {
                errorStr = "responseBody: " + new String(responseBody);
            }
            if (error != null) {
                errorStr = errorStr + "Throwable: " + error.getMessage();
            }
            LogUtil.w(gmRequestModel.jsonCls.getName() + "  --> " + statusCode + " errorStr: " + errorStr);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private String getKey() {
        return gmRequestModel.key;
    }


    private void handleData(String responseString) {
//        LogUtil.i("handleData %s", responseString);
//        if (BuildConfig.DEBUG) {
//            File file = new File(Environment.getExternalStorageDirectory().toString() + "/log");
//            if (!file.exists()) {
//                file.mkdirs();
//            } else {
//                FileUtil.saveToSDCard("/log/" + System.currentTimeMillis() + ".txt", responseString);
//            }
//        }

        try {

            T jsonData = (T) JsonUtil.getInstance().getGson().fromJson(responseString, gmRequestModel.jsonCls);

            if (jsonData != null) {

                onGMSuccess(jsonData);
                LogUtil.d("%s", "key is " + getKey() + " cacheEnabled " + gmRequestModel.cacheMode);
                //保存cache
                if (!StringUtils.isEmpty(getKey())) {

                    if (CacheMode.NO_CACHE != gmRequestModel.cacheMode) {
                        //这里存的是解析后的直接就能用的对象。好处有两个，加载缓存时不用重新解析，还有就是存储的size变小。直接存json数据如果有6k，存解析后就是1.5k
                        CacheApi.getInstance().writeCache(getKey(), jsonData);
                    }

                }


            } else {
                LogUtil.w("%s", "gson parse null ");
            }
        } catch (JsonParseException e) {
            e.printStackTrace();
            //josn解析异常暂不通知终端，仅打印log。json解析异常不应该发生
            //onFail(getResult(ShijibangCode.JSON_PARER_ERROS，"json parse error"));
            LogUtil.e("%s", "gson parse error ,please confirm javabean extends ResultModel");
        }
    }

    public abstract void onGMSuccess(T data);


    public void onCacheData(T data) {
    }


    /**
     * 请求成功，但数据异常，默认弹出toast。如果不想谈，去掉super.
     *
     * @param resultModel
     */
    public void onGMFail(ResultModel resultModel) {
        GMToastUtil.showToast(resultModel.message);
    }


    /**
     * 网络请求异常，默认弹出toast。如果不想谈，去掉super.
     *
     * @param resultModel
     */
    public void onNetFail(ResultModel resultModel) {
        GMToastUtil.showToast(resultModel.message);
    }


}
